package com.yami.shop.im.hanlder;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.StrUtil;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.platform.model.YamiSysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author LGH
 */
@Component
public class SecurityHandler {

    @Autowired
    private TokenStore tokenStore;

    /**
     * 获取用户
     */
    public YamiUser getUser(String token) {
        UserInfoInTokenBO userInfoInTokenBO = null;
        if (StrUtil.isBlank(token)) {
            // 删除该用户在该系统当前的token
            userInfoInTokenBO = AuthUserContext.get();
        } else {
            userInfoInTokenBO = tokenStore.getUserInfoByAccessToken(Base64Decoder.decodeStr(token), true);
        }

        YamiUser yamiUser = new YamiUser();
        yamiUser.setUserId(userInfoInTokenBO.getUserId());
        return yamiUser;
    }

    /**
     * 获取用户
     */
    public YamiShopUser getShopUser(String token) {
        UserInfoInTokenBO userInfoInTokenBO = null;
        if (StrUtil.isBlank(token)) {
            // 删除该用户在该系统当前的token
            userInfoInTokenBO = AuthUserContext.get();
        } else {
            userInfoInTokenBO = tokenStore.getUserInfoByAccessToken(Base64Decoder.decodeStr(token), true);
        }
        YamiShopUser details = new YamiShopUser();
        details.setUserId(userInfoInTokenBO.getUserId());
        details.setEnabled(userInfoInTokenBO.getEnabled());
        details.setShopId(userInfoInTokenBO.getShopId());
        details.setEmployeeId(userInfoInTokenBO.getOtherId());
        return details;
    }

    /**
     * @param token 用户token
     * @return 用户信息
     */
    public YamiSysUser getSysUser(String token) {
        UserInfoInTokenBO userInfoInTokenBO = null;
        if (StrUtil.isBlank(token)) {
            // 删除该用户在该系统当前的token
            userInfoInTokenBO = AuthUserContext.get();
        } else {
            userInfoInTokenBO = tokenStore.getUserInfoByAccessToken(Base64Decoder.decodeStr(token), true);
        }
        YamiSysUser details = new YamiSysUser();
        details.setUserId(Long.valueOf(userInfoInTokenBO.getUserId()));
        details.setEnabled(userInfoInTokenBO.getEnabled());
        details.setUsername(userInfoInTokenBO.getNikeName());
        details.setEmployeeId(userInfoInTokenBO.getOtherId());
        return details;
    }

}
